package WEB.JDBC;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
 * @ClassName JDBCDemo
 * @Description JDBC事务
 * @Author 2214361854
 * @Date 2022/3/9 14:31
 * @Version 1.0
 */
public class JDBCDemo2 {
    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://localhost:3306/abc?serverTimezone=UTC&?useUnicode=true&characterEncoding=utf8&useSSL=false";
        String username = "root";
        String password = "root";
        Connection coon = DriverManager.getConnection(url, username, password);

        //定义SQL
        String sql1 = "update student set sex='男' where id=1";
        String sql2 = "update student set sex='女' where id=2";

        //获取执行SQL对象
        Statement statement = coon.createStatement();

        try {
            //开启事务
            coon.setAutoCommit(false);
            //执行SQL
            int cont1 = statement.executeUpdate(sql1);
            int cont2 = statement.executeUpdate(sql2);
            //处理结果
            System.out.println(cont1);
            System.out.println(cont2);

            //提交事务
            coon.commit();
        } catch (Exception throwables) {
            //回滚事务
            coon.rollback();
            throwables.printStackTrace();
        }finally {
            //释放资源
            statement.close();
            coon.close();
        }
    }
}
